library(tidyverse) # for data cleaning and plotting
library(googlesheets4) # for reading googlesheet data
library(lubridate) # for date manipulation
library(openintro) # for the abbr2state() function
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
library(ggmap) # for mapping points on maps
library(gplots) # for col2hex() function
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
library(leaflet) # for highly customizable mapping
library(ggthemes) # for more themes (including theme_map())
library(plotly) # for the ggplotly() - basic interactivity
library(gganimate) # for adding animation layers to ggplots
library(transformr) # for "tweening" (gganimate)
library(shiny) # for creating interactive apps
gs4_deauth() # To not have to authorize each time you knit.
library(scales) # for helpful labeling
library(gifski)
library(ggimage)
theme_set(theme_minimal())
# SNCF Train data
small_trains <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-02-26/small_trains.csv")
# Lisa's garden data
garden_harvest <- read_sheet("https://docs.google.com/spreadsheets/d/1DekSazCzKqPS2jnGhKue7tLxRU3GVL1oxi-4bEM5IWw/edit?usp=sharing") %>%
mutate(date = ymd(date))
# Lisa's Mallorca cycling data
mallorca_bike_day7 <- read_csv("https://www.dropbox.com/s/zc6jan4ltmjtvy0/mallorca_bike_day7.csv?dl=1") %>%
select(1:4, speed)
# Heather Lendway's Ironman 70.3 Pan Am championships Panama data
panama_swim <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_swim_20160131.csv")
panama_bike <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_bike_20160131.csv")
panama_run <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_run_20160131.csv")
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
Go here or to previous homework to remind yourself how to get set up.
Once your repository is created, you should always open your project rather than just opening an .Rmd file. You can do that by either clicking on the .Rproj file in your repository folder on your computer. Or, by going to the upper right hand corner in R Studio and clicking the arrow next to where it says Project: (None). You should see your project come up in that list if you’ve used it recently. You could also go to File –> Open Project and navigate to your .Rproj file.
Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
NEW!! With animated graphs, add eval=FALSE to the code chunk that creates the animation and saves it using anim_save(). Add another code chunk to reread the gif back into the file. See the tutorial for help.
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
ggplotly() function.lettuce_graph <- garden_harvest %>%
filter(vegetable == "lettuce") %>%
group_by(vegetable, variety) %>%
summarize(count = n()) %>%
arrange(desc(count)) %>%
ggplot(aes(x = count, y = fct_reorder(variety, count),
text = variety)) +
geom_bar(stat = "identity", fill = "darkturquoise", color = "white") +
labs(title = "The Harvest of Each Varieties of Lettuce",
x = "Count",
y = "Variety")
ggplotly(lettuce_graph,
tooltip = c("text","x"))
covid_graph <- covid19 %>%
filter(state %in% c("Minnesota","Wisconsin","Iowa","North Dakota","South Dakota")) %>%
group_by(state, date) %>%
summarize(total_case = cumsum(cases)) %>%
ggplot(aes(x = date, y = total_case, color = state)) +
geom_line() +
labs(title = "Cumulative Case Count")
ggplotly(covid_graph)
small_trains dataset that contains data from the SNCF (National Society of French Railways). These are Tidy Tuesday data! Read more about it here.I want to find the total number of late arrivals of trains departing from Paris Lyon to each destination over years.
train_anim <- small_trains %>%
filter(departure_station == "PARIS LYON") %>%
group_by(year, departure_station, arrival_station) %>%
summarize(total_num_arriving_late = sum(num_arriving_late)) %>%
filter(!arrival_station %in% c("LAUSANNE", "BARCELONA", "ZURICH", "ITALIE")) %>% # They are missing in some of the years
na.omit() %>%
ggplot(aes(x = total_num_arriving_late,
y = fct_reorder(arrival_station,
total_num_arriving_late,
.desc = FALSE))) +
geom_col() +
labs(title = "Total num of late arrivals from Paris Lyon over years",
subtitle = "Year: {closest_state}",
x = "",
y = "") +
transition_states(year)
anim_save("2_train.gif", train_anim)
knitr::include_graphics("2_train.gif")
geom_area() examples here). You will look at cumulative harvest of tomato varieties over time. You should do the following:garden_harvest data, filter the data to the tomatoes and find the daily harvest in pounds for each variety.fct_reorder()) from most to least harvested (most on the bottom).I have started the code for you below. The complete() function creates a row for all unique date/variety combinations. If a variety is not harvested on one of the harvest dates in the dataset, it is filled with a value of 0.
tomato_harvest <- garden_harvest %>%
filter(vegetable == "tomatoes") %>%
group_by(date, variety) %>%
summarize(daily_harvest_lb = sum(weight)*0.00220462) %>%
ungroup() %>%
complete(variety, date, fill = list(daily_harvest_lb = 0)) %>%
group_by(variety) %>%
mutate(cum_harvest_lb = cumsum(daily_harvest_lb))
tomato_anim <- tomato_harvest %>%
ggplot(aes(x = date,
y = cum_harvest_lb)) +
geom_area(aes(fill = fct_reorder(.f = variety,
.x = cum_harvest_lb,
.fun = max,
.desc = FALSE)),
position = "stack") +
labs(title = "Cumulative harvest of tomato varieties over time",
x = "Date",
y = "Cum harvest (lb)",
fill = "Variety") +
transition_reveal(date)
anim_save("3_tomato.gif", tomato_anim)
knitr::include_graphics("3_tomato.gif")
mallorca_bike_day7 bike ride using animation! Requirements:ggmap.ggimage package and geom_image to add a bike image instead of a red point. You can use this image. See here for an example.mallorca <- get_stamenmap(
bbox = c(left = 2.2, bottom = 39.4, right = 2.9, top = 39.8),
maptype = "terrain",
zoom = 11)
bike_image <- "https://raw.githubusercontent.com/llendway/animation_and_interactivity/master/bike.png"
bike_anim <-
ggmap(mallorca) +
# geom_point(data = mallorca_bike_day7,
# aes(x = lon, y = lat),
# color = "red") +
geom_path(data = mallorca_bike_day7,
aes(x = lon, y = lat, color = ele),
size = 4) +
geom_image(data = mallorca_bike_day7 %>%
mutate(image = bike_image),
aes(image = image)) +
labs(title = "Mallorca bike route",
subtitle = "Time: {frame_along}") +
scale_color_viridis_c(option = "magma") +
theme_map() +
theme(legend.background = element_blank()) +
transition_reveal(time)
anim_save("4_bike.gif", bike_anim)
knitr::include_graphics("4_bike.gif")
The animation is better than static map in this situation, because the animation shows the overall path dynamically.
panama_swim, panama_bike, and panama_run. Create a similar map to the one you created with my cycling data. You will need to make some small changes: 1. combine the files (HINT: bind_rows(), 2. make the leading dot a different color depending on the event (for an extra challenge, make it a different image using `geom_image()!), 3. CHALLENGE (optional): color by speed, which you will need to compute on your own from the data. You can read Heather’s race report here. She is also in the Macalester Athletics Hall of Fame and still has records at the pool.panama_all <- bind_rows(panama_swim, panama_bike, panama_run)
# swim_image <- "https://github.com/llendway/animation_and_interactivity/blob/master/swimmer.jpg"
# bike_image <- "https://raw.githubusercontent.com/llendway/animation_and_interactivity/master/bike.png"
# run_image <- "https://github.com/llendway/animation_and_interactivity/blob/master/runner.png"
panama <- get_stamenmap(
bbox = c(left = -79.6, bottom = 8.91, right = -79.5, top = 8.99),
maptype = "terrain",
zoom = 14)
panama_anim <-
ggmap(panama) +
geom_point(data = panama_all,
aes(x = lon, y = lat, color = event),
size = 3) +
geom_path(data = panama_all,
aes(x = lon, y = lat),
size = .6) +
labs(title = "Panama triathlete route",
subtitle = "Time: {frame_along}") +
scale_color_manual(values=c("red1", "sienna2", "dodgerblue3")) +
theme_map() +
theme(legend.background = element_blank()) +
transition_reveal(time)
anim_save("5_panama.gif", panama_anim)
knitr::include_graphics("5_panama.gif")
lag() function you’ve used in a previous set of exercises). Replace missing values with 0’s using replace_na().geom_path() and add a group aesthetic. Put the x and y axis on the log scale and make the tick labels look nice - scales::comma is one option. This plot will look pretty ugly as is.geom_point()) and add the state name as a label (geom_text() - you should look at the check_overlap argument).animate() function to have 200 frames in your animation and make it 30 seconds long.covid_lag <- covid19 %>%
group_by(state) %>%
mutate(case_lag_7day = lag(cases, 7, order_by = date)) %>%
replace_na(list(case_lag_7day = 0)) %>%
mutate(new_case = cases - case_lag_7day) %>%
filter(cases >= 20)
covid_gganim <- covid_lag %>%
ggplot(aes(x = cases, y = new_case, group = state)) +
geom_point() +
geom_path() +
geom_text(aes(label = state), check_overlap = TRUE) +
scale_x_log10(labels = comma) +
scale_y_log10(labels = comma) +
labs(title = "Trajectory of US COVID-19 Confirmed Cases",
subtitle = "Date: {frame_along}",
x = "Totel Confirmed Cases",
y = "New Confirmed Cases (in the Past Week)") +
transition_reveal(date)
animate(covid_gganim, nframes = 200, duration = 30)
anim_save("6_covid.gif", covid_gganim)
knitr::include_graphics("6_covid.gif")
I saw some bounces on the graph, which shows that the total cases are continuously increasing.
wday() to create a day of week variable and filter to all the Fridays. HINT: use group = date in aes().census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot)
states_map <- map_data("state")
cases_10000 <- covid19 %>%
left_join(census_pop_est_2018,
by = "state") %>%
mutate(day = wday(date, label = TRUE)) %>%
filter(day == "Fri") %>%
mutate(cases_per_10000 = (cases/est_pop_2018)*10000,
state = str_to_lower(state))
covid_gganim2 <-
cases_10000 %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state,
fill = cases_per_10000,
group = date)) +
expand_limits(x = states_map$long, y = states_map$lat) +
labs(title = "cumulative cases per 10000 people over time",
subtitle = "Date: {frame_time}",
fill = "Cases per 10000") +
scale_fill_viridis_c(option = "plasma") +
theme_map() +
theme(legend.background = element_blank()) +
transition_time(date)
animate(covid_gganim2, duration = 15)
anim_save("7_covid.gif", covid_gganim2)
knitr::include_graphics("7_covid.gif")
shiny app (for next week!)NOT DUE THIS WEEK! If any of you want to work ahead, this will be on next week’s exercises.
app.R file you create. Below, you will post a link to the app that you publish on shinyapps.io. You will create an app to compare states’ cumulative number of COVID cases over time. The x-axis will be number of days since 20+ cases and the y-axis will be cumulative cases on the log scale (scale_y_log10()). We use number of days since 20+ cases on the x-axis so we can make better comparisons of the curve trajectories. You will have an input box where the user can choose which states to compare (selectInput()) and have a submit button to click once the user has chosen all states they’re interested in comparing. The graph should display a different line for each state, with labels either on the graph or in a legend. Color can be used if needed.DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?